<?php
require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/views/GeneralView.php');
require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/models/interfaces/Invoice.php');
require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/daos/InvoiceDAO.php');
require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/controlers/interfaces/IController.php');

/**
 * @access public
 * @author Edgar Morán
 * @package Aplicación.controlers
 */
class InvoicesController implements IController {
	/**
	 * @AssociationType Aplicación.views.GeneralView
	 * @AssociationKind Composition
	 */
	public $_generalView;
	/**
	 * @AssociationType Aplicación.models.interfaces.IInvoice
	 * @AssociationKind Composition
	 */
	public $_iInvoice;
	/**
	 * @AssociationType Aplicación.daos.InvoiceDAO
	 * @AssociationKind Composition
	 */
	public $_invoiceDAO;
    
    /**
     * Default constructor for class
     */
    public function InvoicesController(){
        $this->_generalView = null;
        $this->_iInvoice = null;
        $this->_invoiceDAO = new InvoicesDAO();
    }

	/**
	 * @access public
	 * @param int aClientId
	 * @param array aInvoiceProducts
	 * @return int
	 * @ParamType aClientId int
	 * @ParamType aInvoiceProducts array
	 * @ReturnType int
	 */
	public function addInvoice() {
        
       /*  invoices
            id
            date
            clientsId
            status (ac, ca)
            
            invoices_products
            id
            quantity
            price
        */   
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();// Not yet implemented
		$view = new View(TPLaddInvoice);
		$util = new Validations();
		$successMessage= NULL;
		
		$view->tpl->pageTitle="Crear Factura";
		$view->tpl->actionTitle="Crear factura";
		$view->tpl->actionError=false;
        
		$params['idTypes']= array(
			array(
		      "value" => '',
		      "name" => 'Seleccione el tipo de Identificación',
		      "selected" => true
		    ),
		    array(
		      "value" => '1',
		      "name" => 'CC',
		      "selected" => false
		    ),
		    array(
		      "value" => '2',
		      "name" => 'CE',
		      "selected" => false
		    ),
		    array(
		      "value" => '3',
		      "name" => 'NIT',
		      "selected" => false
		    ),
		);
        
		//si se va a agregar una factura
    	if(!empty($params['submit'])){
            
            $aClientId = $params['clientId'];
            $aInvoiceProducts = $params['invoiceProducts'];

            if($this->validateClientParams($aClientId, $aInvoiceProducts)){
                if($this->_invoiceDAO->existUserId($aClientId))
                {
                    //AQUI VOY!!!
                    $this->_iClient = new PhoneClient($aIdType, $aClientId, $aName, $aLastName, $aAddress, $aPhone, $aEmail);
                    if($this->_clientsDAO->addClient($this->_iClient))
                        setCookieLive ("MensajeExito", str_replace('$', $aName." ".$aLastName, SUCCESSAddClient) , time()+3600);
                        //echo "si";
    					header('Location:'.ADDCLIENT);                }
                else{
                    $view->tpl->actionError=ERRORDB;
                }
            }
            else {
                //error con los parámetros de entrada
				$seletecValue=$util->array_search_key($params['idType'],$params['idTypes']);
				if(!empty($seletecValue)){
					$params['idTypes'][0]['selected']=false;
					$params['idTypes'][$seletecValue['value']]['selected']=true;
				}
				$view->tpl->actionError=ERRORGeneral;
				$view->tpl->actionErrors=$this->_actionErrors;
            }
			
		}
		else{
			if(isset($_COOKIE['MensajeExito']))
				$successMessage=$_COOKIE['MensajeExito'];
			removeCookieLive('MensajeExito');
		}
		$view->tpl->params=$params;
		$view->tpl->successMessage=$successMessage;
		//$view->tpl->categoryList =
		$result = $view->render();    
		$fc->setBody($result);
        
	}

	/**
	 * @access public
	 * @param int aId
	 * @return boolean
	 * @ParamType aId int
	 * @ReturnType boolean
	 */
	public function cancelInvoice($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		return $this->_invoiceDAO->cancelInvoice($aId);
	}

	/**
	 * @access public
	 * @param int aId
	 * @return IInvoice
	 * @ParamType aId int
	 * @ReturnType IInvoice
	 */
	public function getInvoice($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		$invoice = $this->_invoiceDAO->getInvoice($aId);
        if ($invoice != false){
            $clientInf = $this->_invoiceDAO->getInvoiceClient($aId);
            $client = new PhoneClient($clientInf['idType'], $clientInf['clientId'], $clientInf['name'], $clientInf['lastName'], $clientInf['address'], $clientInf['phone'], $clientInf['email'], $clientInf['access'], $clientInf['id']);//TODO revisar los parametros y la creación del objeto
            
            $this->_iInvoice = new Invoice($invoice['date'], $client);
            
            $products = $this->_invoiceDAO->getInvoiceProducts($aId);
            for($i=0; $i < sizeof($products); $i++){
                $prod = new Product($products[$i]['code'], $products[$i]['reference'], $products[$i]['description'], $products[$i]['presentation'], $products[$i]['picture'], $products[$i]['stock'], $products[$i]['minStock'], $products[$i]['price'], $products[$i]['access']);
                $invProd = new InvoiceProduct($prod, $products[$i]['quantity'], $products[$i]['totalPrice'], $aId);
                $this->_iInvoice->addProduct($prod);
            }
            return $this->_iInvoice;
        }
        return false;
	}

	/**
	 * @access public
	 * @return array
	 * @ReturnType array
	 */
	public function getInvoices() {
		return $this->_invoiceDAO->getInvoices();
	}

	/**
	 * @access public
	 * @return void
	 * @ReturnType void
	 */
	public function printInvoicesList() {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @param int aId
	 * @return void
	 * @ParamType aId int
	 * @ReturnType void
	 */
	public function printInvoice($aId) {
		// Not yet implemented
	}
}
?>